<template>
  <div v-if="visible" class="change-password-mask" @click.self="close">
    <div class="change-password-popup">
      <div class="change-password-header">
        <span>{{ $t('components.changePassword.title') }}</span>
        <span class="change-password-close" @click="close">×</span>
      </div>
      
      <div class="change-password-content">
     
        <template v-if="email">
          <div class="security-label">{{ $t('components.changePassword.account') }}</div>
        <div class="change-password-form-row">
          <i class="iconfont icon-yonghu"></i>
          <input class="change-password-input" v-model="account" :placeholder="$t('components.changePassword.accountPlaceholder')" />
        </div>
        </template>
        
        <div class="security-label">{{ $t('components.changePassword.cityQuestion') }}</div>
        <div class="change-password-form-row">
          <i class="iconfont icon-xiaoxi"></i>
          <input class="change-password-input" v-model="city" :placeholder="$t('components.changePassword.answerPlaceholder')" />
        </div>
        
        <div class="security-label">{{ $t('components.changePassword.jobQuestion') }}</div>
        <div class="change-password-form-row">
          <i class="iconfont icon-xiaoxi"></i>
          <input class="change-password-input" v-model="job" :placeholder="$t('components.changePassword.answerPlaceholder')" />
        </div>
        
        <div class="security-label">{{ $t('components.changePassword.newPassword') }}</div>
        <div class="change-password-form-row">
          <i class="iconfont icon-mima"></i>
          <input type="password" class="change-password-input" v-model="newPassword" :placeholder="$t('components.changePassword.newPasswordPlaceholder')" />
        </div>
        
        <div class="security-label">{{ $t('components.changePassword.confirmPassword') }}</div>
        <div class="change-password-form-row">
          <i class="iconfont icon-mima"></i>
          <input type="password" class="change-password-input" v-model="confirmPassword" :placeholder="$t('components.changePassword.confirmPasswordPlaceholder')" />
        </div>
        
        <div class="change-password-btn-row">
          <button class="change-password-btn" @click="onSubmit">
            <span style="font-size: 28px;">✓</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineExpose, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

// 使用备用翻译系统
let t = (key) => key
let setLang = (newLang) => {}

// 创建响应式的翻译函数
const translationVersion = ref(0)
const $t = (key) => {
  // 依赖translationVersion来触发响应式更新
  translationVersion.value
  return t(key)
}

// 初始化翻译函数
const initTranslations = async () => {
  try {
    const fallback = await import('../utils/i18n-fallback')
    t = fallback.t
    setLang = (newLang) => {
      fallback.setLang(newLang)
      translationVersion.value++
    }
    // 监听语言变化事件
    window.addEventListener('language-changed', () => {
      translationVersion.value++
    })
  } catch (error) {
    console.warn('Failed to load i18n fallback:', error)
  }
}
const router = useRouter()
const visible = ref(false)
const city = ref('')
const job = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const account = ref('')

const props = defineProps({
  email: {
    type: Boolean,
    default: false
  }
})

const open = (prefilledAccount = '') => {
  visible.value = true
  // 重置表单
  city.value = ''
  job.value = ''
  newPassword.value = ''
  confirmPassword.value = ''
  account.value = prefilledAccount || ''
}

const close = () => {
  visible.value = false
}

const onSubmit = () => {
  let trimmedAccount = account.value.trim()
  // 邮箱格式正则表达式
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  // 手机号格式正则表达式（支持11位数字，1开头）
  const phoneRegex = /^1[3-9]\d{9}$/
  
  // 检查是否为有效的邮箱或手机号
  const isValidEmail = emailRegex.test(trimmedAccount)
  const isValidPhone = phoneRegex.test(trimmedAccount)
  

  if (props.email) {
  // 验证表单
    if (!account.value.trim()) {
      window.messageRef?.show($t('components.changePassword.pleaseEnterAccount'), 'error')
      return
    }
    if (!isValidEmail && !isValidPhone) {
    window.messageRef?.show($t('components.changePassword.invalidAccountFormat'), 'error')
    return
  }
   }

  



  
  if (!city.value.trim()) {
    window.messageRef?.show($t('components.changePassword.pleaseEnterCity'), 'error')
    return
  }
  
  if (!job.value.trim()) {
    window.messageRef?.show($t('components.changePassword.pleaseEnterJob'), 'error')
    return
  }
  
  if (!newPassword.value.trim()) {
    window.messageRef?.show($t('components.changePassword.pleaseEnterNewPassword'), 'error')
    return
  }
  
  if (newPassword.value.length < 5 || newPassword.value.length > 20) {
    window.messageRef?.show($t('login.passwordLength'), 'error')
    return
  }
  
  if (newPassword.value !== confirmPassword.value) {
    window.messageRef?.show($t('components.changePassword.passwordMismatch'), 'error')
    return
  }
  if (!props.email) {
    trimmedAccount = localStorage.getItem('email')
   }
  // 这里调用修改密码的接口
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
  window.request?.('/system/user/resetPwd4Forget', {
    method: 'PUT',
    body: {
      userId: userInfo.id,
      firstAnswer: city.value,
      secondAnswer: job.value,
			newPassword: newPassword.value,
			username: trimmedAccount
    }
  }).then(res => {
		window.messageRef?.show($t('components.changePassword.changeSuccess'), 'success')
    // localStorage.setItem('password', newPassword.value)
    
    // 设置标记，表示刚修改过密码，避免登录页面自动填充
    sessionStorage.setItem('passwordChanged', 'true')
    
    router.push('/login')
    close()
  }).catch(err => {
    window.messageRef?.show($t('components.changePassword.changeFailed') + ': ' + (err.message || $t('errors.internalError')), 'error')
  })
}

onMounted(async () => {
  await initTranslations()
})

defineExpose({ open, close })
</script>

<style scoped>
.change-password-mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  z-index: 3000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.change-password-popup {
  width: 500px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  animation: popupIn 0.3s ease-out;
}

@keyframes popupIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.change-password-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.change-password-close {
  font-size: 24px;
  color: #888;
  cursor: pointer;
  transition: color 0.2s;
}

.change-password-close:hover {
  color: #5cc2e6;
}

.change-password-content {
  padding: 24px;
}

.security-label {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
  margin-top: 20px;
}

.security-label:first-child {
  margin-top: 0;
}

.change-password-form-row {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 0 16px;
  margin-bottom: 16px;
  transition: border-color 0.2s;
}

.change-password-form-row:focus-within {
  border-color: #5cc2e6;
}

.change-password-form-row i {
  font-size: 18px;
  color: #888;
  margin-right: 12px;
}

.change-password-input {
  flex: 1;
  height: 48px;
  border: none;
  background: transparent;
  font-size: 16px;
  color: #333;
  outline: none;
}

.change-password-input::placeholder {
  color: #aaa;
}

.change-password-btn-row {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.change-password-btn {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: none;
  background: linear-gradient(135deg, var(--theme-secondary) 0%, var(--theme-secondary-hover) 100%);
  color: #fff;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 16px rgba(92, 194, 230, 0.3);
}

.change-password-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 20px rgba(92, 194, 230, 0.4);
}

.change-password-btn:active {
  transform: scale(0.95);
}
</style> 